package com.yun.zf.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.yun.zf.admin.service.*;
import com.yun.zf.common.admin.dto.house.House;
import com.yun.zf.common.admin.dto.house.HouseCertificateDto;
import com.yun.zf.common.admin.dto.house.OwnerCertificateDto;
import com.yun.zf.common.admin.model.house.*;
import com.yun.zf.common.admin.model.search.CommunitySearchMo;
import com.yun.zf.common.admin.model.search.HouseSearchMo;
import com.yun.zf.common.annotation.LogPrint;
import com.yun.zf.common.app.domain.ZfCommunity;
import com.yun.zf.common.app.domain.ZfHouseBasic;
import com.yun.zf.common.esRes.CommunityResMo;
import com.yun.zf.common.esRes.HouseIndexResMo;
import com.yun.zf.common.mapstruct.admin.HouseMapper;
import com.yun.zf.common.vo.Response;
import com.yun.zf.system.redis.RedisCache;
import com.yun.zf.system.security.utils.SecurityUtils;
import com.yun.zf.system.service.ISysDictDataService;
import com.yun.zf.system.service.PermissionService;
import com.yun.zf.system.utils.AliyunOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/system/house")
@Api(value = "", tags = "房源管理")
@Log
public class ZfHouseController  extends  BaseController{

    @Autowired
    private ZfHouseDetailService houseDetailService;
    @Autowired
    private AliyunOssUtil ossUtil;
    @Autowired
    private ZfHouseBasicService houseBasicService;
    @Autowired
    private ZfCommunityService communityService;

    @Autowired
    private ZfHouseDescService houseDescService;
    @Autowired
    private ZfHouseDocumentInfoService documentInfoService;
    @Autowired
    private ZfHouseInfoService houseInfoService;
    @Autowired
    private ZfHouseCertificateService houseCertificateService;
    @Autowired
    private ZfOwnerCertificateService ownerCertificateService;
    @Autowired
    private ZfCommunitySubwayService communitySubwayService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private ZfDeptCommunityService deptCommunityService;
    @Autowired
    private ZfHousePictureService pictureService;
    @Autowired
    private RedisCache redisCache;


    @PostMapping("/getHouseForMini")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "业主委托列表")
    @ApiOperationSupport(order = 2)
    @LogPrint(description = "业主委托列表")
    public Response getHouseForMini() {

        // 1 获取当前业务员部门所维护的小区列表
        List<Long> dcIds = deptCommunityService.getCommunitys( SecurityUtils.getLoginUser().getDeptId());

        return Response.success( houseBasicService.getUnmaintainhouseBasic(dcIds,prov,aCode));
    }

    @PostMapping("/submitMaintain")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "申请维护")
    @ApiOperationSupport(order = 2)
    @LogPrint(description = "申请维护")
    public Response submitMaintain(@RequestBody Map<String,String>map) {
        try {
            int count = houseBasicService.updateStatusForMaintain(Long.parseLong(map.get("houseId")) ,Long.parseLong(map.get("cityCode")),Long.parseLong(map.get("provCode")));
            if (count>0){
                return Response.success("申请成功");
            }
        }catch (Exception e){
            return Response.error("申请失败");
        }
        return Response.error("申请失败");
    }

    @PostMapping("/communitySuggestForHouse")
    @ApiOperation(value = "房源录入自动补全小区信息")
    public Response communitySuggestForHouse(@RequestBody Map<String,String>map) {
        List<Map<String, String>> suggests = communityService.communitySuggestToHouse(map.get("title"), aCode);
        return Response.success(suggests);
    }


    @PostMapping("/searchHouseBasic")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "搜索房源信息")
    @ApiOperationSupport(order = 1)
    @LogPrint(description = "搜索房源信息")
    public Response searchHouseBasic(@Validated @RequestBody HouseSearchMo houseSearchMo) {
        // 取当前城市
        houseSearchMo.setCityCode(String.valueOf(aCode));
        // 如果是地铁搜索，则先找到地铁线路下的所有小区
        if (StringUtils.isNotEmpty(houseSearchMo.getContext())||StringUtils.isNotEmpty(houseSearchMo.getSubway())|| StringUtils.isNotEmpty(houseSearchMo.getStations())) {
            CommunitySearchMo communitySearchMo = HouseMapper.INSTANCE.searchHouseToCommunity(houseSearchMo);
            // 获得地铁站下的小区ID
            Map<String, Object> community = communityService.searchCommunitys(communitySearchMo);
            if (community == null) {
                return Response.success("未搜索到符合条件的数据");
            }
            //2、查询小区基本信息
            List<CommunityResMo> esResList = (List<CommunityResMo>) community.get("records");
            if (esResList.size() <= 0) {
                return Response.success("未查询到符合条件的小区信息");
            }
            StringBuilder sb = new StringBuilder();
            for (CommunityResMo res : esResList) {
                sb.append(res.getCid()).append(",");
            }
            // 将小区集合字符串赋值给搜索对象
            houseSearchMo.setCommunityId(sb.toString());
        }
        //1、 获取ES 中的房源id信息
        Map<String, Object> map = houseBasicService.searchHouseBasic(houseSearchMo);
        if (map == null) {
            return Response.error("未搜索到数据");
        }
        //2、 根据ID 查询列表信息
        List<HouseIndexResMo> sourceList = (List) map.get("records");
        List<Long> ids = new ArrayList<>();
        if (sourceList.size() <= 0) {
            return Response.error("未搜索到数据");
        }
        for (HouseIndexResMo hmap : sourceList) {
            ids.add(hmap.getHid());
        }
        Long proCode = sourceList.get(0).getProvinceCode();
        Long cityCode = sourceList.get(0).getCityCode();
        List<HouseListMo> houseListMos = houseBasicService.houseBasic(proCode, cityCode, ids);
        // 列表信息覆盖原data id 信息
        map.put("records", houseListMos);
        return Response.success(map);
    }

    @PostMapping("/getHouseAllInfo")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "查询详情")
    @ApiOperationSupport(order = 2)
    @LogPrint(description = "查询详情")
    public Response<House> getHouseAllInfo(@RequestBody Map<String,String>map) {
        if (StringUtils.isBlank(map.get("houseId"))){
            return  Response.error("缺少必要参数");
        }
        House houseInfo = houseBasicService.getHouseAllInfo(Long.parseLong(map.get("houseId")),prov ,aCode);

        return Response.success(houseInfo);
    }


    @PostMapping("/addBasicHouseInfo")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "录入房源基本信息")
    @ApiOperationSupport(ignoreParameters = {"id"}, order = 3)
    @LogPrint
    public Response addBasicHouseInfo(@Validated @RequestBody HouseBasicMo houseBasicMo) {
            houseBasicMo.setCityCode(aCode);
            houseBasicMo.setProvinceCode(prov);

        // 1：验证小区信息是否正确
        ZfCommunity community = communityService.getCommunity(Long.parseLong(houseBasicMo.getCommunityId()), houseBasicMo.getProvinceCode(), houseBasicMo.getCityCode());
        if (community == null) {
            return Response.error("没有查到对应的小区信息");
        }
        ZfHouseBasic houseBasic = HouseMapper.INSTANCE.moToHouseBasic(houseBasicMo);
        //2、录入基本信息，房源状态更改为待实勘
        houseBasic.setStatus("checking");
        houseBasic.setCommunity(community.getCommunityName());
        //3、设置城市信息
        houseBasic.setProvinceName(community.getProvinceName());
        houseBasic.setCityName(community.getCityName());
        houseBasic.setRegionCode(community.getRegionCode());
        houseBasic.setStreetCode(community.getStreetCode());
        houseBasic.setRegionName(community.getRegionName());
        houseBasic.setStreetName(community.getStreetName());
        // 4、设置维护经纪人工号
        int agentNo = SecurityUtils.getLoginUser().getAgentNo();
        houseBasic.setRecordUser(agentNo);
        houseBasic.setRecordName(SecurityUtils.getLoginUser().getAgentName());
        houseBasic.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        houseBasic.setRecordTool("manager");
        // 1：新增房源基础信息
        Long houseId = houseBasicService.addHouseBasic(houseBasic);
        if (houseId == 0L) {
            return Response.error("房源添加异常");
        }
        Map<String,String> map = new HashMap<>();
        map.put("id",String.valueOf(houseId));
        return Response.success(map);
    }

    /**
     * 我维护的房源
     *
     * @return
     */
    @PostMapping("/getMaintainHouse")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "我维护的房源")
    @ApiOperationSupport(order = 4)
    public Response getMaintainHouse(@RequestBody Map<String,Integer> map) {
        if (map.isEmpty()){
            map= new HashMap<>();
            map.put("current",1);
            map.put("pageSize",3);
        }
        // 1、维护经纪人工号
        int agentNo = SecurityUtils.getLoginUser().getAgentNo();
        Page<HouseListMo> houseBasics = houseBasicService.houseBasic(prov, aCode, agentNo,map.get("current"),map.get("pageSize"),map.get("type"));
        return Response.success(houseBasics);
    }

    @PostMapping("/addHouseDetailInfo")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "录入房源补充信息")
    @ApiOperationSupport(order = 5)
    public Response addHouseDetailInfo(@Validated @RequestBody HouseDetailMo houseDetail) {
        try {
            // 查询缓存是否存在
          Boolean hasKey =  redisCache.hasKey("detail"+houseDetail.getBasicId());
          if (hasKey){
              return Response.error("请勿重复提交");
          }
          // 设置缓存房源id
          redisCache.setCacheObject("detail"+houseDetail.getBasicId(),houseDetail.getBasicId(),1L, TimeUnit.MINUTES);
          // 查询是否已经添加数据，如果已经添加，则不可以重复添加
          ZfHouseBasic basic = houseBasicService.getHouseBasic(houseDetail.getBasicId(), prov, aCode);
            if (basic == null) {
                return Response.error("确认房屋是否存在");
            }
            int detailCount = houseDetailService.addHouseDetailInfo(houseDetail,basic.getType(),prov,aCode);
            if (detailCount <= 0) {
                return Response.error("信息录入失败");
            }
            Map<String,String> map = new HashMap<>();
            map.put("id",houseDetail.getBasicId().toString());
            map.put("title",houseDetail.getTitle());
            return Response.success(map);
        } catch (Exception e) {
            return Response.error("补充信息异常，请稍后在试！");
        }
    }




    @PostMapping("/getHouseDetail")
    @ApiOperation(value = "查询维护信息")
    @ApiOperationSupport(order = 4)
    public Response getHouseDetail(@RequestBody Map<String,String> map) {
        HouseDetailMo detailMo  = houseDetailService.getHouseDetai(Long.parseLong(map.get("houseId")),prov,aCode);
        return Response.success(detailMo);
    }


    @PostMapping("/motifyHouseInfo")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "补充维护信息")
    @ApiOperationSupport(order = 6)
    public Response motifyHouseInfo(@RequestBody HouseInfo houseInfo) {
        Boolean hasKey =  redisCache.hasKey("houseInfo"+houseInfo.getBasicId());
        if (hasKey){
            return Response.error("提交频繁，请1分钟后重新提交");
        }
        // 设置缓存房源id
        redisCache.setCacheObject("houseInfo"+houseInfo.getBasicId(),houseInfo.getBasicId(),1L, TimeUnit.MINUTES);

        // 1、验证数据数据是否符合租赁或者出售，如果是租赁，不可传出售节点，如果是出售不可传租赁节点信息
        ZfHouseBasic basic = houseBasicService.getHouseBasic(Long.parseLong(houseInfo.getBasicId()) , prov, aCode);
        if (basic == null) {
            return Response.error("确认房屋是否存在");
        }

        int count = 0;
        if (houseInfo.getInfoId() != null) {
            count = houseInfoService.motifyHouseInfo(houseInfo, basic.getType(),prov,aCode);
        } else {
            count = houseInfoService.addHouseInfo(houseInfo, basic.getType(),prov,aCode);
        }
        if (count > 0) {
            return Response.success("更新成功");
        }
        return Response.error("数据更新失败");
    }

    /**
     * 查询维护信息
     *
     * @param
     * @return
     */
    @PostMapping("/getHouseInfo")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "查询维护信息")
    @ApiOperationSupport(order = 7)
    public Response<HouseInfo> getHouseInfo(@RequestBody Map<String,String>map ) {
        if (StringUtils.isBlank(map.get("houseId"))){
            return  Response.error("缺少必要参数");
        }
        HouseInfo houseInfo = houseInfoService.getHouseInfoById(Long.parseLong(map.get("houseId")), prov, aCode);

        return Response.success(houseInfo);
    }


    /**
     * 新增或者更新房源特色
     *
     * @param houseDesc
     * @return
     */
    /*
    {
	"basicId": 1366728372445732865,
	"cityCode": 420100,
	"description": "[{\"title\":\"核心卖点\",\"content\":\"证满两年，无增值税。视野开阔，可看江。清水毛坯，随便装\"}]",
	"provinceCode": 420000
}
     */
    @PostMapping("/motifyHouseDesc")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "补充房源特色")
    @ApiOperationSupport(order = 8)
    public Response motifyHouseDesc(@RequestBody HouseDescMo houseDesc) {
        Boolean hasKey =  redisCache.hasKey("houseDesc"+houseDesc.getBasicId());
        if (hasKey){
            return Response.error("请勿重复提交");
        }
        // 设置缓存房源id
        redisCache.setCacheObject("houseDesc"+houseDesc.getBasicId(),houseDesc.getBasicId(),1L, TimeUnit.MINUTES);

        Boolean flage = checkMotifyData(Long.parseLong(houseDesc.getBasicId()) , prov, aCode);
        if (!flage) {
            return Response.error("确认房源信息是否存在");
        }

        int count = 0;
        if (StringUtils.isNotBlank(houseDesc.getId())) {
            count = houseDescService.motifyHouseDes(houseDesc,prov,aCode);
        } else {
            count = houseDescService.addHouseDes(houseDesc,prov,aCode);
        }
        if (count > 0) {
            return Response.success("更新成功");
        }
        return Response.error("数据更新失败");
    }


    @PostMapping("/getHouseDesc")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "查询房源特色信息")
    @ApiOperationSupport(order = 9)
    public Response getHouseDesc(@RequestBody Map<String,String>map) {
        if (StringUtils.isBlank(map.get("houseId"))){
            return  Response.error("缺少必要参数");
        }
        HouseDescMo houseDesc = houseDescService.getHouseDes(Long.parseLong(map.get("houseId")), prov, aCode);
        // 查询同小区房源描述

        return Response.success(houseDesc);
    }


    /*
    {
  "id": "1420575145155682305",
    "basicId": "1418826207411089409",
    "registrationDate": "2017-02-23",
    "isShare": "N",
    "constructionArea": 70,
    "actualArea": 90,
    "certType": 1,
    "certNumber": "343430995",
    "owner": "诸葛孔明",
    "address": "天涯海角sddd",
    "remark": "测试数dd据",
    "documentInfoMoList": [
      {

        "path": "/test/33333.jpg",
        "url": "wwww.etet/test/33333.jpg"
      }
    ]
}
     */
    @PostMapping("/motifyHouseDocumentInfo")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "补充房源证件")
    @ApiOperationSupport(order = 10)
    public Response motifyHouseDocumentInfo(@RequestBody HouseCertificateMo houseCertificateMo) {
        Boolean flage = checkMotifyData(Long.parseLong(houseCertificateMo.getBasicId()), prov, aCode);
        if (!flage) {
            return Response.error("请确认房源是否存在");
        }
        int sum = 0;
        if (StringUtils.isNotBlank(houseCertificateMo.getId())&&!"0".equals(houseCertificateMo.getId())) {
            sum = houseCertificateService.motifyHouseCertificate(houseCertificateMo,prov,aCode);
        } else {
            sum = houseCertificateService.addHouseCertificate(houseCertificateMo,prov,aCode);
        }
        if (sum <= 0) {
            return Response.error("上传信息失败");
        }
        return Response.success("提交成功");
    }

    @PostMapping("/getHouseDocumentInfo")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "查询房源产证信息")
    @ApiOperationSupport(order = 11)
    public Response getHouseDocumentInfo(@RequestBody Map<String,String>map) {
        if (StringUtils.isBlank(map.get("houseId"))){
            return  Response.error("缺少必要参数");
        }
        // 查询产证信息
        HouseCertificateDto dto= houseCertificateService.getHouseCertificate(Long.parseLong(map.get("houseId")), prov, aCode);

        return Response.success(dto);
    }

    /*{
        "id": "1420623847509471233",
            "basicId": "1418826207411089409",
            "type": 1,
            "certificateType": 1,
            "citizenship": "中国",
            "ownerName": "测试名11字",
            "ownerCardNo": "4201000000000",
            "certificateStart": "2010-02-09",
            "certificateEnd": "2040-02-09",
            "iphone": "11010010000",
            "email": "33344@qq.com",
            "sex": "男",
            "birthday": "1995-12-1",
            "documentInfoList": [
        {
            "did": "1420623846632861698",
                "path": "/test/33333.jpg",
                "url": "wwww.etet/test/33333.jpg"
        }
    ]
    }*/
    @PostMapping("/motifyOwnerCertificate")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "补充业主身份证信息")
    @ApiOperationSupport(order = 12)
    public Response motifyOwnerCertificate(@RequestBody OwnerCertificateMo ownerCertificate) {
        Boolean flage = checkMotifyData(Long.parseLong(ownerCertificate.getBasicId()), prov, aCode);
        if (!flage) {
            return Response.error("您没有权限修改当前数据");
        }
        int sum = 0;
        if (StringUtils.isNotBlank(ownerCertificate.getId())&&!"0".equals(ownerCertificate.getId())) {
            sum = ownerCertificateService.motifyOwnerCertificate(ownerCertificate,prov,aCode);
        } else {
            sum = ownerCertificateService.addOwnerCertificate(ownerCertificate,prov,aCode);
        }
        if (sum <= 0) {
            return Response.error("身份证信息上传失败");
        }
        return Response.success("提交成功");
    }

    @PostMapping("/getOwnerCertificate")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @ApiOperation(value = "查询业主证件信息")
    @ApiOperationSupport(order = 13)
    public Response getOwnerCertificate(@RequestBody Map<String,String>map) {
        if (StringUtils.isBlank(map.get("houseId"))){
            return  Response.error("缺少必要参数");
        }
        // 查询产证信息
        OwnerCertificateDto dto = ownerCertificateService.getOwnerCertificate(Long.parseLong(map.get("houseId")), prov, aCode);
        return Response.success(dto);
    }

    @PostMapping("/submitShikan")
    @ApiOperation(value = "实勘图提交")
    @ApiOperationSupport(order = 17)
    public Response submitShikan(@RequestBody Map<String,String>map) {
        if (StringUtils.isBlank(map.get("shikan"))|| StringUtils.isBlank(map.get("huxing"))){
            return  Response.error("缺少必要参数");
        }
      String sk =  map.get("shikan");
      String hx = map.get("huxing");
      pictureService.editShikan(sk,hx,prov,aCode);
        return Response.success();
    }


    @PostMapping("/shikanPic")
    @ApiOperation(value = "实勘图查询")
    @ApiOperationSupport(order = 17)
    public Response shikanPic(@RequestBody Map<String,String>map) {
        if (StringUtils.isBlank(map.get("houseId"))){
            return  Response.error("缺少必要参数");
        }
        return Response.success(pictureService.getPics(Long.parseLong( map.get("houseId")),prov,aCode));
    }


    /**
     *
     * @return
     * 验证当前修改的房源是否存在
     */
    public Boolean checkMotifyData(Long basicId, Long provCode, Long cityCode) {
        int agentNo = SecurityUtils.getLoginUser().getAgentNo();
        if (basicId == -1L) {
            return true;
        }
        int count = houseBasicService.selectCountByBasicId(basicId, provCode, cityCode, agentNo);
        return count > 0 ? true : false;
    }

    @PostMapping("/houseBaiscToEs")
    @ApiOperation(value = "房源发布")
    public Response houseBaiscToEs(@RequestBody Map<String,String>map) {
        if (StringUtils.isBlank(map.get("houseId"))){
            return  Response.error("缺少必要参数");
        }
        try {
           return   houseBasicService.houseToEs(Long.parseLong(map.get("houseId")) ,prov,aCode);
        } catch (Exception e) {

        }
        return Response.error("推送失败");
    }


}
